package com.example.smartall.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.smartall.R;
import com.example.smartall.adapter.UserInfoListAdapter;
import com.example.smartall.api.Api;
import com.example.smartall.api.ApiConfig;
import com.example.smartall.api.NetCallBack;
import com.example.smartall.diaglog.ChangInfoDialog;
import com.example.smartall.diaglog.LoadedDialog;
import com.example.smartall.entity.UserInfoBean;
import com.example.smartall.ui.base.BaseActivity;
import com.example.smartall.utils.Constant;
import com.example.smartall.utils.SPUtils;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Author: abbas
 * @CreateDate:
 * @Description: 个人信息页面
 * <p>
 * 标签栏显示本页面标题，点击返回图标可返回到上一页，点击修改可保存修改的信息，可修改内容为：头像、昵称、性别、联系电话，注：证件号只显示前两位与后四位数字其他使用 * 号代替。
 * <p>
 * 上传头像 第一个问题
 */
public class UserInfoActivity extends BaseActivity {
    private ListView lvUserInfo;
    private Button btChange;
    private ImageView imBack;
    private TextView tvTitle;

    private List<String> userInfo;
    private UserInfoListAdapter adapter;
    private MHandler handler;
    private Uri uri;
    private SuccessBean successBean;
    private UserInfoBean.UserBean userBean = new UserInfoBean.UserBean();

    private SPUtils spUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        spUtils = new SPUtils(this, Constant.SP_USER_FILE_NAME);
        handler = new MHandler();

        init();
        initEvent();
    }

    @Override
    public void init() {
        lvUserInfo = (ListView) findViewById(R.id.lv_userInfo);
        imBack = (ImageView) findViewById(R.id.im_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        btChange = findViewById(R.id.bt_change);

        tvTitle.setText("个人信息");

        userInfo = new ArrayList<>();
        userInfo.add(spUtils.getString(Constant.USER_AVATAR));
        userInfo.add(spUtils.getString(Constant.USER_ID));
        userInfo.add(spUtils.getString(Constant.USER_NAME));
        userInfo.add(spUtils.getString(Constant.USER_NICKNAME));
        userInfo.add(spUtils.getString(Constant.USER_EMAIL));
        userInfo.add(spUtils.getString(Constant.USER_PHONENUMBER));
        userInfo.add("0".equals(spUtils.getString(Constant.USER_SEX)) ? "男" : "女");
        userInfo.add(spUtils.getString(Constant.USER_ID_CARD));
        userInfo.add(spUtils.getString(Constant.USER_BALANCE));
        userInfo.add(spUtils.getString(Constant.USER_SCORE));

        adapter = new UserInfoListAdapter(this, userInfo);
        lvUserInfo.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void initEvent() {
        imBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UserInfoActivity.this.finish();
            }
        });
        //及其麻烦
        lvUserInfo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0 || i == 3 || i == 5 || i == 6) {

                } else {
                    return;
                }
                if (i == 0) {
                    int REQUEST_CODE_CONTACT = 101;
                    String[] permissions = {
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
                    //验证是否许可权限
                    for (String str : permissions) {
                        if (UserInfoActivity.this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                            //申请权限
                            UserInfoActivity.this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                        }
                    }
                    //更换头像操作
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 0);

                } else {
                    ChangInfoDialog dialog = new ChangInfoDialog(UserInfoActivity.this);
                    dialog.setListener(new ChangInfoDialog.OnWhichClickListener() {
                        @Override
                        public void onOkClick(String s) {
                            switch (i) {
                                case 3:
                                    userBean.setNickName(s);
                                    break;
                                case 5:
                                    userBean.setPhonenumber(s);
                                    break;
                                case 6:
                                    userBean.setSex("男".equals(s) ? "0" : "1");
                                    break;
                            }
                            changeUserInfo(i,s);
                        }
                    });
                    dialog.show();
                }
            }
        });
    }

    private void changeUserInfo(int which,String changeString) {
        final LoadedDialog dialog = new LoadedDialog(getThis());
        dialog.show();
        Api.config(ApiConfig.CHANGE_USER_URL, null)
                .putRequest(new NetCallBack() {
                                @Override
                                public void onSuccess(String res) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            switch (which){
                                                case 0x01:
                                                    spUtils.putString(Constant.USER_AVATAR, ApiConfig.MIDDLE_AVATER_URL + successBean.fileName);
                                                    UserInfoActivity.this.init();
                                                    break;
                                                case 0x03:
                                                    spUtils.putString(Constant.USER_NICKNAME, changeString);
                                                    UserInfoActivity.this.init();
                                                    break;
                                                case 0x05:
                                                    spUtils.putString(Constant.USER_PHONENUMBER, changeString);
                                                    UserInfoActivity.this.init();
                                                    break;
                                                case 0x06:
                                                    spUtils.putString(Constant.USER_SEX, "男".equals(changeString) ? "0" : "1");
                                                    UserInfoActivity.this.init();
                                                    break;
                                            }
                                            dialog.dismiss();
                                        }
                                    });
                                    showToastSync("修改成功");
                                }

                                //这代码好看的我想吐
                                @Override
                                public void onFailure(Exception e) {
                                    showToastSync(e.toString());
                                }
                            }, UserInfoActivity.this
                        , new Gson().toJson(userBean));
    }

    /**
     * @Author: abbas
     * @CreateDate: 2022/2/14
     * @Description: 整了我n天，泪目，竟然是我不审api
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_OK:
                if (data != null) {
//                    LoadedDialog dialog = new LoadedDialog(UserInfoActivity.this);
//                    dialog.show();
//                    File en = Environment.getExternalStorageDirectory();
                    String path = getFilePathFromContentUri(data.getData(), this);

                    upLoadAvater(new File(path));


//                    MultipartBody multipartBody = new MultipartBody.Builder()
//                            .setType(MultipartBody.FORM)
//                            .addFormDataPart("avater",file.getName(), RequestBody.create(file, MediaType.parse("application/from-data")))
//                            .build();
//                    Request request = new Request.Builder()
//                            .url(ApiConfig.BASE_URL + ApiConfig.LOAD_FILE)
//                            .addHeader(Constant.POST_TOKEN,new SPUtils(UserInfoActivity.this,Constant.SP_USER_FILE_NAME).getString(Constant.TOKEN))
//                            .post(multipartBody)
//                            .build();
//                    OkHttpClient client = new OkHttpClient();
//                    client.newCall(request).enqueue(new Callback() {
//                        @Override
//                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
//                            Log.i("tag",e.toString());
//                        }
//
//                        @Override
//                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//                            String res = response.body().string();
//                            Log.e("tag",res);
//                        }
//                    });


//                    String path = "";
//                    path = getFilePathFromContentUri(data.getData(), this);
//
//                    File file = new File(path);


//                    OkHttpClient client = new OkHttpClient();
//                    final RequestBody body = new MultipartBody.Builder()
//                            .setType(MultipartBody.FORM)
//                            .addFormDataPart("avater",file.getName(),RequestBody.create(MediaType.parse("image/jpeg"),file))
//                            .build();
//                    Request request = new Request.Builder()
//                            .url(ApiConfig.BASE_URL + ApiConfig.LOAD_FILE)
//                            .addHeader("Content-Type","multipart/form-data")
//                            .addHeader(Constant.POST_TOKEN,new SPUtils(UserInfoActivity.this,Constant.SP_USER_FILE_NAME).getString(Constant.TOKEN))
//                            .post(body)
//                            .build();
//                    Call call = client.newCall(request);
//                    call.enqueue(new Callback() {
//                        @Override
//                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
//                            showToastSync("网络错误");
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    dialog.dismiss();
//                                }
//                            });
//                        }
//
                    /**
                     * Date:     2022/2/10
                     * Description:  {"msg":null,"code":500}
                     *               Response{protocol=http/1.1, code=200, message=, url=http://124.93.196.45:10001/prod-api/common/upload}
                     */
//                        @Override
//                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//                            String res = response.body().string();
//                            Log.i("tag", res);
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    dialog.dismiss();
//                                }
//                            });
//                        }
//                    });


//                    if (!TextUtils.getInstances().isEmpty(path)) {
//                        Bitmap bitmap = getSmallBitmap(path, 200, 200);
//                    }
                }
                break;
        }
    }

    private void upLoadAvater(File file){
        final LoadedDialog dialog = new LoadedDialog(UserInfoActivity.this);
        dialog.show();
        OkHttpClient client = new OkHttpClient.Builder().build();
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(Constant.POST_TOKEN, SPUtils.config(UserInfoActivity.this, Constant.SP_USER_FILE_NAME).getString(Constant.TOKEN))
                .addFormDataPart("file", file.getName(), requestBody)
                .build();
        Request request = new Request.Builder()
                .url(ApiConfig.BASE_URL + ApiConfig.LOAD_FILE)
                .addHeader(Constant.POST_TOKEN, SPUtils.config(UserInfoActivity.this, Constant.SP_USER_FILE_NAME).getString(Constant.TOKEN))
                .post(multipartBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String res = response.body().string();
                Log.i("tag", res);
                successBean = new Gson().fromJson(res, SuccessBean.class);
                if (successBean != null && successBean.getCode() == 200) {
                    handler.sendEmptyMessage(0x01);
                } else {
                    showToastSync("上传失败");
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    public static String getFilePathFromContentUri(Uri uri, Context context) {
        String filePath;
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};
        Cursor cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
        if (cursor == null) return null;
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }
//
//    public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {
//        final BitmapFactory.Options options = new BitmapFactory.Options();
//        options.inJustDecodeBounds = true;
//        try {
//            BitmapFactory.decodeFile(filePath, options);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
//        options.inJustDecodeBounds = false;
//        return BitmapFactory.decodeFile(filePath, options);
//    }
//
//    public static int calculateInSampleSize(BitmapFactory.Options options,
//                                            int reqWidth, int reqHeight) {
//        final int height = options.outHeight;
//        final int width = options.outWidth;
//        int inSampleSize = 1;
//        if (height > reqHeight || width > reqWidth) {
//            final int heightRatio = Math.round((float) height / (float) reqHeight);
//            final int widthRatio = Math.round((float) width / (float) reqWidth);
//            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
//        }
//        return inSampleSize;
//    }

    class MHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0x01:
                    userBean.setAvatar(ApiConfig.MIDDLE_AVATER_URL + successBean.getFileName());
                    changeUserInfo(0x01,successBean.getFileName());
                    break;
                default:
                    UserInfoActivity.this.init();
            }
        }
    }

    public static class SuccessBean {

        /**
         * msg : 操作成功
         * fileName : /profile/upload/2022/02/14/41595575-490d-49ac-a10e-38e059c3be96.jpg
         * code : 200
         * url : http://124.93.196.45/profile/upload/2022/02/14/41595575-490d-49ac-a10e-38e059c3be96.jpg
         */

        private String msg;
        private String fileName;
        private int code;
        private String url;

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }
}